package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.github.pagehelper.util.StringUtil;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author laoYe
 * @date 2025-10-27
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    private static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        LoginVo loginVo = new LoginVo();
        //1 获取openid
        String openId = wechatService.getOpenId(dto.getCode());
        //2 获取用户的手机号码
        String phone = wechatService.getPhoneNumber(dto.getPhoneCode());
        //3根据openid查询用户信息
        FamilyMember memberInDB = lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        //创建一个新的FamilyMember对象，将手机号码设置进去
        FamilyMember newFamilyMember = new FamilyMember();
        newFamilyMember.setPhone(phone);
        //4 判断用户是否存在
        if (memberInDB != null) {
            loginVo.setNickName(memberInDB.getName());
            //5 存在 判断手机号码是否有变更，若有变更应及时更新
            if (!phone.equals(memberInDB.getPhone())) {
                //uodate
                newFamilyMember.setId(memberInDB.getId());
                //通过id更新
                updateById(newFamilyMember);
            }
        } else {
            //6 不存在，新增 将openid设置进去
            newFamilyMember.setOpenId(openId);
            //昵称，随机生成，加手机后四位
            String nickname = generateNickName(phone);
            newFamilyMember.setName(nickname);
            save(newFamilyMember);
        }

        //7 把用户的id和昵称封装到jwt令牌中，返回token给前端
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userid", newFamilyMember.getId());
        claims.put("nickName", newFamilyMember.getName());
        tokenService.createToken(claims);
        loginVo.setToken(openId);
        return loginVo;
    }

    private String generateNickName(String phone) {
        Random r = new Random();
        int prefixIndex = r.nextInt(DEFAULT_NICKNAME_PREFIX.size());
        //手机号后四位
        String suffix = phone.substring(phone.length() - 4);
        return DEFAULT_NICKNAME_PREFIX.get(prefixIndex) + suffix;
    }
}
